import React, { Component } from "react";
import "../assets/css/CommodityDetail.css";
import PageHeader from "../components/PageHeader";
import login from "../hooks/loginInfo";
import { successToast, errorToast } from "../components/Toast";
import Loading from "../components/Loading";

class CommodityDetail extends Component {
  constructor(props) {
    super(props);

    this.state = {
      productInfo: null,
      sugarList: null,
      temList: null,
      milkList: null,
      creamList: null,
      currentCream: 0,
      currentMilk: 0,
      currentSugar: 0,
      currentTem: 0,
      descList: null,
      num: 1,
      collect: false,
      shopBagNum: null,
      token: null,
    };
    this.changeNum = this.changeNum.bind(this);
    this.collection = this.collection.bind(this);
    this.ToShopbag = this.ToShopbag.bind(this);
    this.addShopBag = this.addShopBag.bind(this);
  }

  addShopBag(flag) {
    if (this.state.token) {
      var attr = ["cream", "milk", "sugar", "tem"];
      var list = ["creamList", "milkList", "sugarList", "temList"];
      var current = [
        "currentCream",
        "currentMilk",
        "currentSugar",
        "currentTem",
      ];
      var str = "";
      attr.forEach((item, index) => {
        if (this.state.productInfo[item]) {
          str += this.state[list[index]][this.state[current[index]]] + "/";
        }
      });
      this.$axios
        .post("/addShopcart", {
          pid: this.state.productInfo.pid,
          count: this.state.num,
          tokenString: this.state.token,
          rule: str.slice(0, -1),
        })
        .then((res) => {
          flag
            ? this.$axios.post("/modifyShopcartCount",{
              tokenString:this.state.token,
              sid:res.data.sid,
              count:this.state.num
            }).then(()=>{
              this.props.history.push({
                pathname:"/orderDetail",
                query:{
                  sid:[res.data.sid]
                }
              })
            })
             
            : successToast(res.data.msg);
          this.$axios
            .get("/shopcartCount", {
              params: {
                tokenString: this.state.token,
              },
            })
            .then((res) => {
              this.setState({
                shopBagNum: res.data.result,
              });
            });
        });
    } else {
      this.props.history.push("/login");
      errorToast("请先登录您的账号");
    }
  }

  ToShopbag() {
    if (this.state.token) {
      this.props.history.push("/cart");
    } else {
      this.props.history.push("/login");
      errorToast("请先登录您的账号");
    }
  }

  collection() {
    if (this.state.token) {
      if (this.state.collect) {
        this.$axios
          .post("/notlike", {
            pid: this.state.productInfo.pid,
            tokenString: this.state.token,
          })
          .then((res) => {
            successToast(res.data.msg);
            this.setState({
              collect: false,
            });
          });
      } else {
        this.$axios
          .post("/like", {
            pid: this.state.productInfo.pid,
            tokenString: this.state.token,
          })
          .then((res) => {
            successToast(res.data.msg);
            this.setState({
              collect: true,
            });
          });
      }
    } else {
      this.props.history.push("/login");
      errorToast("请先登录您的账号");
    }
  }

  changeNum(symbol) {
    var num;
    if (symbol === "-") {
      num = this.state.num - 1;
      if (num <= 0) {
        num = 1;
      }
      this.setState({
        num,
      });
    } else {
      num = this.state.num + 1;
      this.setState({
        num,
      });
    }
  }
  componentWillMount() {
    var loginInfo = login();
    this.$axios
      .get("/productDetail", {
        params: {
          pid: this.props.match.params.id,
        },
      })
      .then((res) => {
        this.paramsList(res.data.result[0]);
        this.setState({
          productInfo: res.data.result[0],
          token: loginInfo.token,
        });
      });
    if (loginInfo.isLogin) {
      this.$axios
        .get("/findlike", {
          params: {
            pid: this.props.match.params.id,
            tokenString: loginInfo.token,
          },
        })
        .then((res) => {
          this.setState({
            collect: res.data.result.length,
          });
        });
      this.$axios
        .get("/shopcartCount", {
          params: {
            tokenString: loginInfo.token,
          },
        })
        .then((res) => {
          this.setState({
            shopBagNum: res.data.result,
          });
        });
    }
  }

  paramsList(data) {
    var sugarList = data.sugar.split("/");
    var temList = data.tem.split("/");
    var milkList = data.milk.split("/");
    var creamList = data.cream.split("/");
    var descList = data.desc.split("\n");
    this.setState({
      sugarList,
      temList,
      milkList,
      creamList,
      descList,
    });
  }

  render() {
    return (
      <div className="CommodityDetail">
        <PageHeader>
          <span slot="title">商品详情</span>
        </PageHeader>
        {this.state.productInfo ? (
          <div className="CommodityDetail_content">
            <div className="CommodityDetail_content_cover">
              <img src={this.state.productInfo.large_img} alt="" />
              <span className="CommodityDetail_content_name">
                {this.state.productInfo.name}
              </span>
            </div>
            <div className="CommodityDetail_content_introduce">
              <div className="CommodityDetail_content_introduce_params">
                {this.state.productInfo.cream && (
                  <div>
                    <span>{this.state.productInfo.cream_desc}</span>
                    {this.state.creamList.map((item, index) => {
                      return (
                        <span
                          onClick={() => this.setState({ currentCream: index })}
                          className={
                            this.state.currentCream === index ? "active" : ""
                          }
                          key={index}
                        >
                          {item}
                        </span>
                      );
                    })}
                  </div>
                )}
                {this.state.productInfo.milk && (
                  <div>
                    <span>{this.state.productInfo.milk_desc}</span>
                    {this.state.milkList.map((item, index) => {
                      return (
                        <span
                          onClick={() => this.setState({ currentMilk: index })}
                          className={
                            this.state.currentMilk === index ? "active" : ""
                          }
                          key={index}
                        >
                          {item}
                        </span>
                      );
                    })}
                  </div>
                )}
                {this.state.productInfo.sugar && (
                  <div>
                    <span>{this.state.productInfo.sugar_desc}</span>
                    {this.state.sugarList.map((item, index) => {
                      return (
                        <span
                          onClick={() => this.setState({ currentSugar: index })}
                          className={
                            this.state.currentSugar === index ? "active" : ""
                          }
                          key={index}
                        >
                          {item}
                        </span>
                      );
                    })}
                  </div>
                )}
                {this.state.productInfo.tem && (
                  <div>
                    <span>{this.state.productInfo.tem_desc}</span>
                    {this.state.temList.map((item, index) => {
                      return (
                        <span
                          onClick={() => this.setState({ currentTem: index })}
                          className={
                            this.state.currentTem === index ? "active" : ""
                          }
                          key={index}
                        >
                          {item}
                        </span>
                      );
                    })}
                  </div>
                )}
              </div>
              <div className="CommodityDetail_content_introduce_desc">
                <p className="CommodityDetail_content_introduce_desc_title">
                  商品描述
                </p>
                {this.state.descList.map((item, index) => {
                  return (
                    <p
                      className="CommodityDetail_content_introduce_desc_item"
                      key={index}
                    >
                      {index + 1 + "、" + item}
                    </p>
                  );
                })}
              </div>
              <div className="CommodityDetail_content_introduce_num">
                <div className="CommodityDetail_content_introduce_num_price">
                  ￥
                  {this.state.num * Number(this.state.productInfo.price) +
                    ".00"}
                </div>
                <div className="CommodityDetail_content_introduce_num_stepper">
                  <span onClick={() => this.changeNum("-")}></span>
                  <span>{this.state.num}</span>
                  <span onClick={() => this.changeNum("+")}></span>
                </div>
              </div>
            </div>
            <div className="CommodityDetail_operation">
              <div className="CommodityDetail_operation_my">
                <div onClick={this.ToShopbag}>
                  <i
                    style={{
                      backgroundImage: `url(${
                        require("../assets/images/b.png").default
                      })`,
                    }}
                  ></i>
                  {this.state.shopBagNum && (
                    <span className="dager">{this.state.shopBagNum}</span>
                  )}
                  <span>购物袋</span>
                </div>
                <div>
                  <i
                    style={{
                      backgroundImage: `url(${
                        require("../assets/images/" +
                          (this.state.collect ? "aixin-o" : "aixin") +
                          ".png").default
                      })`,
                    }}
                    onClick={this.collection}
                  ></i>
                  <span>收藏</span>
                </div>
              </div>
              <div className="CommodityDetail_operation_btn">
                <button onClick={() => this.addShopBag(false)}>
                  加入购物袋
                </button>
                <button onClick={() => this.addShopBag(true)}>立即购买</button>
              </div>
            </div>
          </div>
        ) : <Loading></Loading>}
      </div>
    );
  }
}

export default CommodityDetail;
